package com.wisdom.common.monitor;

import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class ServiceMonitor {
//	@Autowired
//	private CounterService counterService;
	@Autowired
	private GaugeService gaugeService;

	@Autowired
	private MetricRegistry mr;

	@Pointcut(value = "@annotation(com.wisdom.common.annotation.WisdomMonitor)")
	private void cutMonitor() {

	}

	/**
	 *
	 * @param joinPoint
	 */
	@Before("cutMonitor()")
	public void ServiceMeter(JoinPoint joinPoint){
		Meter meter = mr.meter(joinPoint.getSignature().toString()+".meter");
		meter.mark();
//		counterService.increment(joinPoint.getSignature().toString()+".count");
	}
	

	@Around("cutMonitor()")
	public Object latencyService(ProceedingJoinPoint pjp) throws Throwable {
		long start = System.currentTimeMillis();
		Object result = pjp.proceed();
		long end = System.currentTimeMillis();
		gaugeService.submit(pjp.getSignature().toString()+".usetime", end - start);
		return result;
	}

}
